const http = require('http');
const fs = require('fs');
const port = 4783;

const server = http.createServer((req, res) => {
  // 读取上一层目录的 backup-log 文件, 然后打印他的最后一行
  // 告诉浏览器我输出的是utf-8编码
  res.setHeader('Content-Type', 'text/plain; charset=utf-8');
  const logFile = './backup-log';
  fs.readFile(logFile, 'utf8', (err, data) => {
    if (err) {
      console.error(err);
      res.end('Error reading log file');
      return;
    }
    const lines = data.split('\n');
    const lastLine = lines[lines.length - 2];
    console.log(lastLine);
    
    res.end(lastLine + '\n');
  })
});

function start() {
  server.listen(port, () => {
    console.log(`Server listening on port ${port}`);
  });
} 

module.exports = {
  start
};
